from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from . import ser,models
from rest_framework.decorators import action
from luffy.utils.response import APIResponse
# Create your views here.


class LoginView(GenericViewSet):
    #普通密码登录
    @action(methods=('post',), detail=False)
    def login(self, request, *args, **kwargs):
        user_ser =ser.UserSerializer(data=request.data, context={'request':request})
        if user_ser.is_valid():
            token = user_ser.context.get('token')
            #login_ser.context['user']是user对象
            username = user_ser.context['user'].username
            # {'code':1, msg:'成功', token:token, username:username}
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=user_ser.errors)
    #校验手机号
    @action(detail=False)
    def check_telephone(self, request, *args, **kwargs):
        import re
        telephone = request.query_params.get('telephone')
        print(telephone)
        if not re.match(('^1[3-9][0-9]{9}$'), telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            models.UserInfo.objects.get(telephone=telephone)
            return APIResponse(code=1)
        except:
            return APIResponse(code=0, msg='手机号不存在')

    #验证码登录
    @action(methods=['POST'], detail=False)
    def code_login(self, request, *args, **kwargs):
        code_ser = ser.CodeUserSerializer(data=request.data)
        if code_ser.is_valid():
            token = code_ser.context['token']
            username= code_ser.context['user'].username
            return APIResponse(token=token, username=username)
        else:
            return APIResponse(code=0, msg=code_ser.errors)

from . import throttlings
# 短信验证码发送
class SendSmsView(GenericViewSet):
    throttle_classes = [throttlings.SmsThrottling, ]
    @action(methods=['GET'], detail=False)
    def send(self, request, *args, **kwargs):
        '''
        发送验证码接口
        :return:
        '''
        import re
        from luffy.libs.tx_sms import get_code, send_message
        from django.core.cache import cache
        from django.conf import settings
        telephone = request.query_params.get('telephone')
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        # 获取手机验证码
        code = get_code()
        result = send_message(telephone, code)
        print(result)
        if result:
            # 验证码保存，保存在缓存中
            # 验证码key为：sms_cache_%s:即 sms_cache_手机号
            cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)  # 缓存时间：180s
            return APIResponse(code=1, msg='验证码发送成功')
        else:
            return APIResponse(code=0, msg='验证码发送失败')



#手机注册功能
class RegisterView(CreateModelMixin,GenericViewSet):
    queryset = models.UserInfo.objects.all()
    serializer_class = ser.RegisterSerializer
    # def create(self, request, *args, **kwargs):
    #     ser=self.get_serializer(data=request.data)
    #     # if ser.is_valid():
    #     #     ser.save()
    #     #     return APIResponse(code=1,msg='注册成功',username=ser.data.get('username'))
    #     # else:
    #     #     return APIResponse(code=0, msg=ser.errors)

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        username = response.data.get('username')
        return APIResponse(code=1, msg='注册成功', username=username)


    # #缓存测试
    # def test(self):
    #     #以后所有的缓存都缓存到redis中
    #     from django.core.cache import cache
    #     cache.set('name', 'Tophan')